# encoding: UTF-8
 
class User < ActiveRecord::Base
  attr_accessible :hashpasswd, :login, :salt, :status, :password, :password_confirmation
  attr_accessor :password_confirmation #VIP
  validates_presence_of :login

  def self.authenticate(login, passwd)
    user = self.find(:first, :conditions=>["login=:login", {:login => login}])
    if user
	     expected_passwd = encrypted_passwd(passwd, user.salt)
	     if user.hashpasswd != expected_passwd
	       user = nil
	     end
    end
	  user
  end
  
  #虚拟属性 相当get set方法
  def password
    @password
  end
  
  def password=(pass)
    return unless pass
    @password = pass
    generate_passwd(pass)
  end
  
  private

  def generate_passwd(pass)
    salt = Array.new(10){rand(1024).to_s(36)}.join
    self.salt, self.hashpasswd = salt, Digest::SHA256.hexdigest(pass + salt)
  end

  def create_new_salt
    self.salt = Array.new(10){rand(1024).to_s(36)}.join
  end

  def self.encrypted_passwd(pass, salt)
    Digest::SHA256.hexdigest(pass + salt)
  end

end
